<template>
	<view class="content fofa">
		<tabnav title="企业模板库" :col="back"></tabnav>
		<view class="wid100 dis disAl coFFF" style="height: 120rpx;" :style="{'background-color':back}">
			<view v-if="userinfo.usertype" class="textCen" style="width: 50%;" @click="setxuaze(1)">
				<view :style="xuaze == 1?'color: #fff;':''">企业自有模板</view>
				<view v-if="xuaze == 1" class="mar-top10 mar" style="width: 60rpx;height: 2rpx;background-color: #fff;"></view>
				<view v-if="xuaze != 1" class="mar-top10 mar" style="width: 60rpx;height: 2rpx;"></view>
			</view>
			<view v-if="userinfo.usertype" class="textCen" style="width: 50%;" @click="setxuaze(2)">
				<view :style="xuaze == 2?'color: #fff;':''">官方模板</view>
				<view v-if="xuaze == 2" class="mar-top10 mar" style="width: 60rpx;height: 2rpx;background-color: #fff;"></view>
				<view v-if="xuaze != 2" class="mar-top10 mar" style="width: 60rpx;height: 2rpx;"></view>
			</view>
			<view v-if="!userinfo.usertype" class="textCen wid100">
				<view :style="xuaze == 2?'color: #fff;':''">官方模板</view>
				<view v-if="xuaze == 2" class="mar-top10 mar" style="width: 60rpx;height: 2rpx;background-color: #fff;"></view>
				<view v-if="xuaze != 2" class="mar-top10 mar" style="width: 60rpx;height: 2rpx;"></view>
			</view>
		</view>
		<view class="wid100 bacFFF" style="height: 148rpx;">
			<view class="wid87 hei100 mar dis disAl disJuB">
				<view class="wid87 dis disAl borRad10" style="height: 71rpx;background-color: #F4F3F3;">
					<view class="dis disJuC" style="width: 20%;">
						<image :src="aurl+icon_list.sousuo" style="width: 31rpx;height: 31rpx;"></image>
					</view>
					<input class="wid80 " @input="suosouInput" placeholder="搜索模板名称"/>
				</view>
				<image :src="aurl+icon_list.shaixuan" style="width: 42rpx;height: 42rpx;"></image>
			</view>
		</view>
		<view v-if="xuaze == 1" class="wid100">
			
			<scroll-view :style="'height: calc(100vh - 148rpx - 120rpx - 90rpx - '+tops+'px);'" @refresherrefresh="onPulling" :refresher-triggered="triggered"
				scroll-y="true" class="scroll-Y" @scrolltolower="lower" :refresher-enabled="true">
				<view class="wid100" v-if="list.length == 0">
					<view class="wid100" style="height: 160rpx;"></view>
					<view class="wid100 textCen">
						<image src="https://www.sign.run/applet/static/wenjian/wushuju.png" style="width: 306rpx;height: 200rpx;"></image>
						<view class="mar-top30 foSi25" style="color: #858585;">请联系企业管理员添加企业自有模板</view>
					</view>
				</view>
				<view v-if="list.length != 0" class="wid87 mar dis disAl disJuB flwa">
					 <!-- @click="tiaozhuan('/pages/template/previewTemplate?id='+item.id)" -->
					<view class="borRad20 bacFFF box1 mar-top30" @click="detail(index)" 
					v-for="(item,index) in list" :key="index"
						style="height: 250rpx;width: 48%;">
						<view class="dis disAl disJuC" style="height: 184rpx;">
							
							<image :src="aurl+item.iconurl" v-if="item.iconurl && item.iconurl != ''" style="width: 134rpx;height: 142rpx;"></image>
							<image :src="aurl+icon_list.ht" v-else style="width: 134rpx;height: 142rpx;"></image>
						</view> 
						<view class="xia"></view>
						<view class="hei60 dis disAl disJuB wid90 mar">
							<view class="wid80 foSi20 overflowHidden">{{item.templateName}}</view>
							<!-- <image v-if="true" src="https://www.sign.run/applet/static/template/shouchang.png" style="width: 31rpx;height: 29rpx;"></image>
							<image v-if="false" src="https://www.sign.run/applet/static/template/shouchang1.png" style="width: 31rpx;height: 29rpx;"></image> -->
						</view>
					</view>
				</view>
				<view style="height: 120rpx;" :style="{'padding-bottom': paddingBottomHeight + 'rpx'}"></view>
			</scroll-view>
		</view>
		<view v-if="xuaze == 2">
			<!-- <view class="wid100 dis disAl" style="height: 148rpx;">
				<scroll-view class="wid87 mar" style="white-space: nowrap;" scroll-x="true" >
					<view v-for="(item,index) in xuanList" :key="index" @click="xuanIndex = index"
						:class="xuanIndex == index?'coFFF':''" :style="xuanIndex == index?'background-color: '+back+';':''"
						class="mar-right20 borRad40 bacFFF" style="padding: 15rpx 30rpx;display: inline-block;">{{item}}</view>
				</scroll-view>
			</view> -->
			<scroll-view :style="'height: calc(100vh - 148rpx - 120rpx - 90rpx - '+tops+'px);'" @refresherrefresh="onPulling" :refresher-triggered="triggered"
				scroll-y="true" class="scroll-Y" @scrolltolower="lower" :refresher-enabled="true">
				<view class="wid100" v-if="list.length == 0">
					<view class="wid100" style="height: 160rpx;"></view>
					<view class="wid100 textCen">
						<image src="https://www.sign.run/applet/static/wenjian/wushuju.png" style="width: 306rpx;height: 200rpx;"></image>
						<view class="mar-top30 foSi25" style="color: #858585;">暂无官方模板</view>
					</view>
				</view>
				<view v-if="list.length != 0" class="wid87 mar dis disAl disJuB flwa">
					<view class="borRad20 bacFFF box1 mar-top30" @click="tiaozhuan('/pages/template/previewTemplate?id='+item.id)" 
					v-for="(item,index) in list" :key="index"
						style="height: 250rpx;width: 48%;">
						<view class="dis disAl disJuC" style="height: 184rpx;">
							<image :src="aurl+item.iconurl" v-if="item.iconurl && item.iconurl != ''" style="width: 134rpx;height: 142rpx;"></image>
							<image :src="aurl+icon_list.ht2" v-else style="width: 134rpx;height: 142rpx;"></image>
						</view>
						<view class="xia"></view>
						<view class="hei60 dis disAl disJuB wid90 mar">
							<view class="wid80 foSi20 overflowHidden">{{item.templateName}}</view>
							<!-- <image v-if="true" src="https://www.sign.run/applet/static/template/shouchang.png" style="width: 31rpx;height: 29rpx;"></image>
							<image v-if="false" src="https://www.sign.run/applet/static/template/shouchang1.png" style="width: 31rpx;height: 29rpx;"></image> -->
						</view>
					</view>
				</view>
				<view style="height: 120rpx;" :style="{'padding-bottom': paddingBottomHeight + 'rpx'}"></view>
			</scroll-view>
		</view>
		<view v-if="userinfo.usertype" :style="{'padding-bottom': paddingBottomHeight + 'rpx'}" class="wid100 dis disAl disJuC poAbs bacFFF box1" 
			style="height: 120rpx;bottom: 0;">
			<view class="dis disAl disJuC coFFF hei80 foSi35 borRad10" @click="toggle('bottom')" 
			:style="'background-color: '+back+';'" style="width: 400rpx;">新建模板</view>
		</view>
		<uni-popup ref="popup" background-color="#fff">
			<view class="hei80 dis disAl disJuC poRel">
				<view class="poAbs hei80 dis disAl" style="left: 40rpx;">
					<image src="https://www.sign.run/applet/static/index/guanbi.png"style="width: 30rpx;height: 30rpx;" @click="guanbi"></image>
				</view>
				<view class="foSi35 fowe600" style="">新建模板</view>
			</view>
			<view class="wid80 mar dis disAl mar-top20" :style="{'padding-bottom': paddingBottomHeight + 'rpx'}" style="justify-content: space-around;">
				<view class="dis disAl disJuC fleDir" @click="wenjian">
					<image src="https://www.sign.run/applet/static/index/weixin.png" style="width: 112rpx;height: 112rpx;"></image>
					<view class=" foSi25 mar-top20">微信文件发起</view>
				</view>
				<view class="dis disAl disJuC fleDir" @click="tiaozhuan('/pages/wode/drafts')">
					<image src="https://www.sign.run/applet/static/index/hetongcaogao.png" style="width: 112rpx;height: 112rpx;"></image>
					<view class=" foSi25 mar-top20">合同草稿发起</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import tabnav from "../common/tabnav/tabnav.vue"
	export default {
		components: {
			tabnav,
		},
		data() {
			return {
				paddingBottomHeight: 0,
				aurl:this.global.url,
				back: uni.getStorageSync('back'),
				backTwo: uni.getStorageSync('backTwo'),
				xuaze: 1,
				suosou: '',
				// 判断是否还在继续输入
				timer: null,
				tops: 0,
				last_page: 0,
				page: 1,
				triggered: false,
				_freshing: false,
				list: [
					// {id: 0},
					// {id: 1}
				],
				xuanList: ["全部","授权","服务/合作","租赁"],
				xuanIndex: 0,
				userinfo:{}, // 这里用使用中token，主要是员工和企业账号发起
				token:'',
				search:{
					templateName:''
				},
				icon_list:{
					moban:'/addon/qianyu_dzq/wechatimg/moban.png',
					sjhticon:'/addon/qianyu_dzq/wechatimg/sjhticon1.png',
					shaixuan:'/addon/qianyu_dzq/wechatimg/shaixuan.png',
					sousuo:'/addon/qianyu_dzq/wechatimg/sousuo.png',
					ht:'/addon/qianyu_dzq/wechatimg/ht.png',
					ht2:'/addon/qianyu_dzq/wechatimg/ht2.png',
				}
			}
		},
		onLoad() {
			this.token = uni.getStorageSync('inuse_userinfo_token') // 使用中token
			this.userinfo = uni.getStorageSync('inuse_userinfo') // 使用中token
			if(!this.userinfo.usertype){
				this.xuaze = 2
			}
			this.get_templates() // 获取模板库
		},
		created() {
			var that = this
			uni.getSystemInfo({
				success: (res) => {
					console.log(res)
					that.tops = res.statusBarHeight
					let model = ['X', 'XR', 'XS', '11', '12', '13', '14', '15'];
					model.forEach(item => {
						//适配iphoneX以上的底部，给tabbar一定高度的padding-bottom
						if(res.model.indexOf(item) != -1 && res.model.indexOf('iPhone') != -1) {
							that.paddingBottomHeight = 40;
						}
					})
				}
			})
		},
		methods: {
			wenjian(){
				let that=this//保留vue实例
				that.$refs.popup.close()
				wx.chooseMessageFile({
					count: 1,//限制选择的文件数量
					type: 'file',//非图片和视频的文件,不选默认为all
					success (res) {
					 const tempFilePaths = res.tempFiles
					 console.log('临时路径',tempFilePaths)
					 let filename = res.tempFiles[0].name
					 //客制化判断文件名,判断是不是xlsx文件,仅为参考,可自行变化
					 if(filename.lastIndexOf('.xlsx')==filename.length-5 || filename.lastIndexOf('.docx')==filename.length-5){
						uni.uploadFile({
							url: that.global.url + 'api/qianyu_dzq/applet_files_contracts_upload',
							header: {
								"token": uni.getStorageSync('token'),
								"site-id": that.global.site_id
							}, //请求token	
							filePath: tempFilePaths[0].path,
							name: 'file',
							success: (res) => {
								var apiresult = JSON.parse(res.data)
								if (apiresult.code == 1) {
									console.log(apiresult.data.url);
									// that.image = apiresult.data.url
								} else {
									uni.showToast({
										title: apiresult.msg,
										icon: 'error'
									})
								}
							},
							fail() {
								uni.showToast({
									title: "网络连接失败",
									icon: 'error'
								})
							}
						});
					 }else{
				         //客制化提示文件类型错误
						 uni.showToast({
							title: '请选择xlsx文件',
							icon:'error',
							duration: 2000
						 });
					 }
				 
					}
				})
			},
			get_templates(){
				console.log('执行啊')
				uni.showLoading({
					title:'加载中...'
				})
				let that = this
				let type = that.xuaze == 1 ? 1 : 0
				uni.request({
					url: that.global.url+'api/qianyu_dzq/applet_template_list',
					method: 'POST',
					header:{'site-id':that.global.site_id,'token':that.token},
					data: {type:type,templateName:that.search.templateName,page: that.page},
					success(res) {
					    let result = res.data
						console.log(result);
					    if(result.code == 1){
							that.last_page = result.data.data.data.current_page
							if (that.page == 1) {
								that.list = result.data.data.data.data
							} else{
								that.list = that.list.concat(result.data.data.data.data)
							}
						   console.log(result.data.data.data.data)
						   console.log(that.list)
					    }else{
					        uni.showToast({
					            title: result.msg,
					            icon:'none',
								duration: 2000
					        })
					    }
					},
					complete() {
						uni.hideLoading()
					}
				})
			},
			toggle(type) {
				uni.showModal({
				        title: '提示',
				        content: '请前往管理后台进行创建',
						showCancel:false,
				        success: function(res) {
				        if (res.confirm) {
				            // 执行确认后的操作
				        } 
				        
				    }
				})
				// open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
				// this.$refs.popup.open(type)
			},
			guanbi(){
				this.$refs.popup.close()
			},
			onPulling(e) {
				var that = this
				if (that._freshing) return;
				that._freshing = true;
				that.triggered = true
				console.log("onpulling", e);
				setTimeout(() => {
					that.triggered = false;
					that._freshing = false;
				}, 3000)
			},
			lower(e) {
				if(this.last_page > this.page){
					this.page++
					this.get_templates()
				}
			},
			tiaozhuan(url){
				this.$refs.popup.close()
				uni.navigateTo({
					url: url
				});
			},
			setxuaze(type){
				this.xuaze = type
				this.page = 1
				this.search.templateName = ''
				this.get_templates()
			},
			detail(index){
				let pdfurl = this.list[index]['pdfUrl'] // pdf文件预览地址
				let template_id = this.list[index]['templateId'] // id
				let that = this
				uni.request({
					url: that.global.url+'api/qianyu_dzq/applet_template_save_pdf',
					method: 'POST',
					header:{'site-id':that.global.site_id,'token':that.token},
					data: {pdfurl: pdfurl,template_id: template_id},
					success(res) {
					    let result = res.data
					    if(result.code == 1){
							console.log(result.data)
							uni.setStorageSync('contract_detail',that.list[index]) // 由于链接里&等符号，所以存缓存读取
							uni.setStorageSync('contract_detail_pdfUrl',result.data)
							uni.navigateTo({
								url:'/pages/template/previewTemplate'
							})
						}else{
					        uni.showToast({
					            title: result.msg,
					            icon:'none',
								duration: 2000
					        })
					    }
					},
					complete() {
						uni.hideLoading()
					}
				})
			},
			suosouInput: function(event) {
				if (this.timer !== null) clearTimeout(this.timer)
				this.timer = setTimeout(() => {
					this.search.templateName = event.target.value
					this.page = 1
					console.log(this.suosou)
					this.get_templates()
				}, 1000)
			},
		}
	}
</script>

<style>
	.content {
		height: 100vh;
		background-color: #F4F3F3;
	}
	.foSi28{
		font-size: 28rpx;
	}
	.xia{
		height: 1rpx;
		background: #E5E5E5;
	}
</style>
